package com.dh.offer;

import org.junit.Assert;
import org.junit.Test;

/**
 * @ClassName: _53_zai_pai_xu_shu_zu_zhong_cha_zhao_shu_zi_lcof
 * @Description: 剑指 Offer 53 - I. 在排序数组中查找数字 I
 * <p>
 * 统计一个数字在排序数组中出现的次数。
 * <p>
 * 示例 1:
 * <p>
 * 输入: nums = [5,7,7,8,8,10], target = 8
 * 输出: 2
 * 示例 2:
 * <p>
 * 输入: nums = [5,7,7,8,8,10], target = 6
 * 输出: 0
 *  
 * <p>
 * 限制：
 * <p>
 * 0 <= 数组长度 <= 50000
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 * @Author: shouzimu
 * @Date: 2020/12/2 10:17
 */
public class _53_zai_pai_xu_shu_zu_zhong_cha_zhao_shu_zi_lcof {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int mid = 0;
        if (nums.length == 0) {
            return 0;
        }
        if (nums.length == 0 || target > nums[right] || target < nums[0]) {
            return 0;
        }
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                if (mid == 0 || nums[mid - 1] != target) {
                    break;
                } else {
                    right = mid - 1;
                }
            }
        }
        if (nums[mid] != target) {
            return 0;
        }
        int res = 0;
        while (mid < nums.length && nums[mid] == target) {
            res++;
            mid++;
        }
        return res;
    }

    @Test
    public void searchTest() {
        Assert.assertEquals(1, search(new int[]{6}, 6));
        Assert.assertEquals(0, search(new int[]{6}, 4));
        Assert.assertEquals(2, search(new int[]{5, 7, 7, 8, 8, 10}, 8));
        Assert.assertEquals(0, search(new int[]{5, 7, 7, 8, 8, 10}, 6));
    }
}
